'use client';

import { useState, useMemo } from 'react';
import Image from 'next/image';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { MessageCircle } from 'lucide-react';
import type { XLayerToken } from '@/types/xlayer';
import { formatPrice, formatMarketCap } from '@/utils/formatters';
import { TokenChatRoom } from './TokenChatRoom';

interface XLayerTokenListProps {
  tokens: XLayerToken[];
  onTokenSelect: (token: XLayerToken) => void;
  onRefresh: () => void;
}

type SortOption = 'newest' | 'oldest' | 'price_high' | 'price_low' | 'market_cap' | 'volume';

export function XLayerTokenList({ tokens, onTokenSelect, onRefresh }: XLayerTokenListProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState<SortOption>('newest');
  const [filter, setFilter] = useState<'all' | 'active' | 'launched' | 'cancelled'>('all');
  const [chatToken, setChatToken] = useState<XLayerToken | null>(null);

  // Filter and sort tokens
  const filteredAndSortedTokens = useMemo(() => {
    const filtered = tokens.filter(token => {
      const matchesSearch = token.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          token.symbol.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          token.description.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesFilter = filter === 'all' || 
                          (filter === 'active' && !token.launched && !token.cancelled) ||
                          (filter === 'launched' && token.launched) ||
                          (filter === 'cancelled' && token.cancelled);
      
      return matchesSearch && matchesFilter;
    });

    // Sort tokens
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'newest':
          return b.createdAt - a.createdAt;
        case 'oldest':
          return a.createdAt - b.createdAt;
        case 'price_high':
          return parseFloat(b.currentPrice || '0') - parseFloat(a.currentPrice || '0');
        case 'price_low':
          return parseFloat(a.currentPrice || '0') - parseFloat(b.currentPrice || '0');
        case 'market_cap':
          return parseFloat(b.marketCap || '0') - parseFloat(a.marketCap || '0');
        case 'volume':
          return parseFloat(b.volume24h || '0') - parseFloat(a.volume24h || '0');
        default:
          return 0;
      }
    });

    return filtered;
  }, [tokens, searchTerm, sortBy, filter]);

  const getStatusBadge = (token: XLayerToken) => {
    if (token.cancelled) {
      return <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-red-400 text-black border-2 border-black">cancelled</span>;
    }
    if (token.launched) {
      return <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-green-400 text-black border-2 border-black">launched</span>;
    }
    if (Date.now() > token.deadline * 1000) {
      return <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-gray-400 text-black border-2 border-black">deadline</span>;
    }
    return <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-blue-400 text-black border-2 border-black">active</span>;
  };

  const getProgressPercentage = (token: XLayerToken) => {
    const raised = parseFloat(token.raisedAmount);
    const target = parseFloat(token.targetAmount);
    return Math.min((raised / target) * 100, 100);
  };

  return (
    <div className="space-y-6">
      {/* Search and Filters */}
      <div className="flex flex-col md:flex-row gap-4">
        <div className="flex-1">
          <input
            type="text"
            placeholder="Search token name, symbol or description..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full px-4 py-2 bg-gray-800 border-2 border-gray-600 text-white placeholder-gray-400 font-mono focus:border-purple-400 focus:outline-none"
            style={{imageRendering: 'pixelated'}}
          />
        </div>
        
        <div className="flex gap-2">
          <select
            value={filter}
            onChange={(e) => setFilter(e.target.value as typeof filter)}
            className="px-4 py-2 bg-gray-800 border-2 border-gray-600 text-white font-mono focus:border-purple-400 focus:outline-none"
            style={{imageRendering: 'pixelated'}}
          >
            <option value="all">All</option>
            <option value="active">Active</option>
            <option value="launched">Launched</option>
            <option value="cancelled">Cancelled</option>
          </select>
          
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as SortOption)}
            className="px-4 py-2 bg-gray-800 border-2 border-gray-600 text-white font-mono focus:border-purple-400 focus:outline-none"
            style={{imageRendering: 'pixelated'}}
          >
            <option value="newest">Newest</option>
            <option value="oldest">Oldest</option>
            <option value="price_high">Price High</option>
            <option value="price_low">Price Low</option>
            <option value="market_cap">Market Cap</option>
            <option value="volume">Volume</option>
          </select>
          
          <button
            onClick={onRefresh}
            className="pixel-btn"
          >
            Refresh
          </button>
        </div>
      </div>

      {/* Token Grid */}
      {filteredAndSortedTokens.length === 0 ? (
        <div className="text-center py-12">
          <div className="text-gray-400 text-lg mb-2">
            {searchTerm || filter !== 'all' ? 'No matching tokens found' : 'No tokens available'}
          </div>
          {searchTerm && (
            <button
              onClick={() => setSearchTerm('')}
              className="pixel-btn"
            >
              Clear Search
            </button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 w-full">
          {filteredAndSortedTokens.map((token) => (
            <div
              key={token.id}
              className="pixel-card transition-transform hover:scale-105 relative"
            >
              {/* Chat Button */}
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setChatToken(token);
                }}
                className="absolute top-3 right-3 bg-purple-600 hover:bg-purple-700 text-white p-2 rounded-full shadow-lg transition-colors z-10"
                title={`Enter ${token.symbol} chat room`}
              >
                <MessageCircle size={16} />
              </button>

              {/* Token Content - Make it clickable for details */}
              <div
                onClick={() => onTokenSelect(token)}
                className="cursor-pointer"
              >
                {/* Header */}
                <div className="flex items-center space-x-3 mb-4">
                  {token.imageUrl ? (
                    <Image
                      src={token.imageUrl}
                      alt={token.name}
                      width={48}
                      height={48}
                      className="rounded-full object-cover"
                    />
                  ) : (
                    <div className="w-12 h-12 bg-gradient-to-br from-purple-400 to-purple-600 flex items-center justify-center" style={{imageRendering: 'pixelated'}}>
                      <span className="text-white font-bold text-lg">
                        {token.symbol.charAt(0).toUpperCase()}
                      </span>
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <h3 className="font-semibold truncate font-body">{token.name}</h3>
                      {getStatusBadge(token)}
                    </div>
                    <p className="text-xs text-gray-400 font-mono">${token.symbol}</p>
                  </div>
                </div>

                {/* Description */}
                <div className="space-y-2 mb-4">
                  <p className="text-xs text-gray-400 line-clamp-2 font-mono">
                    {token.description}
                  </p>
                </div>

              {/* Progress Bar */}
              {!token.launched && !token.cancelled && (
                <div className="mb-4">
                  <div className="flex justify-between text-xs mb-1 font-mono">
                    <span>Fundraising progress</span>
                    <span>{getProgressPercentage(token).toFixed(1)}%</span>
                  </div>
                  <div className="w-full bg-gray-600 h-2 pixel-border">
                    <div
                      className="bg-green-400 h-2 transition-all"
                      style={{ 
                        width: `${getProgressPercentage(token)}%`,
                        imageRendering: 'pixelated'
                      }}
                    />
                  </div>
                  <div className="flex justify-between text-xs text-gray-400 mt-1 font-mono">
                    <span>{token.raisedAmount} OKB</span>
                    <span>Target: {token.targetAmount} OKB</span>
                  </div>
                </div>
              )}

              {/* Stats */}
              <div className="space-y-2 mb-4">
                {token.currentPrice && (
                  <div className="flex justify-between">
                    <span className="text-xs text-gray-400 font-mono">Price</span>
                    <div className="text-right">
                      <span className="text-sm font-bold font-mono">{formatPrice(parseFloat(token.currentPrice))} OKB</span>
                      {token.priceChange24h !== undefined && token.priceChange24h !== null && (
                        <div className={`text-xs font-mono ${
                          token.priceChange24h >= 0 ? 'text-green-400' : 'text-red-400'
                        }`}>
                          {token.priceChange24h >= 0 ? '+' : ''}{token.priceChange24h.toFixed(2)}%
                        </div>
                      )}
                    </div>
                  </div>
                )}
                {token.marketCap && (
                  <div className="flex justify-between">
                    <span className="text-xs text-gray-400 font-mono">Market Cap</span>
                    <span className="text-sm font-bold font-mono">{formatMarketCap(parseFloat(token.marketCap))}</span>
                  </div>
                )}
                {token.volume24h && (
                  <div className="flex justify-between">
                    <span className="text-xs text-gray-400 font-mono">24h Volume</span>
                    <span className="text-sm font-bold font-mono">{parseFloat(token.volume24h).toFixed(2)} OKB</span>
                  </div>
                )}
                {token.holders !== undefined && (
                  <div className="flex justify-between">
                    <span className="text-xs text-gray-400 font-mono">Holders</span>
                    <span className="text-sm font-bold font-mono">{token.holders}</span>
                  </div>
                )}
              </div>

              {/* Footer */}
              <div className="flex justify-between items-center text-xs text-gray-400 font-mono">
                <span>
                  Created {formatDistanceToNow(new Date(token.createdAt * 1000), { 
                    addSuffix: true, 
                    locale: zhCN 
                  })}
                </span>
                {!token.launched && !token.cancelled && (
                  <span>
                    {Date.now() > token.deadline * 1000 
                      ? 'Ended' 
                      : `${Math.ceil((token.deadline * 1000 - Date.now()) / (1000 * 60 * 60 * 24))} days until end`
                    }
                  </span>
                )}
              </div>

              {/* User Holdings */}
              {token.userBalance && parseFloat(token.userBalance) > 0 && (
                <div className="mt-3 pt-3 border-t border-gray-600">
                  <div className="text-xs text-gray-400 font-mono">My Holdings</div>
                  <div className="font-bold text-green-400 font-mono">
                    {parseFloat(token.userBalance).toLocaleString()} {token.symbol}
                  </div>
                  {token.userContribution && (
                    <div className="text-xs text-gray-400 font-mono">
                      Contribution: {token.userContribution} ETH
                    </div>
                  )}
                </div>
              )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* XLayer Token Chat Room - Convert XLayerToken to Token format */}
      {chatToken && (
        <TokenChatRoom
          token={{
            id: chatToken.id,
            mint: chatToken.tokenAddress || '',
            name: chatToken.name,
            symbol: chatToken.symbol,
            decimals: 18,
            supply: '1000000000',
            description: chatToken.description,
            image: chatToken.imageUrl,
            creator: chatToken.creator,
            marketCap: parseFloat(chatToken.marketCap || '0'),
            price: parseFloat(chatToken.currentPrice || '0'),
            holders: chatToken.holders || 0,
            isActive: !chatToken.cancelled,
            website: chatToken.website,
            twitter: chatToken.twitter,
            telegram: chatToken.telegram,
            createdAt: new Date(chatToken.createdAt * 1000).toISOString(),
            updatedAt: new Date(chatToken.createdAt * 1000).toISOString(),
            chain: 'xlayer'  
          }}
          onClose={() => setChatToken(null)}
        />
      )}
    </div>
  );
}